﻿Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_QuanLyHoSo_CapGCN
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim itm As New ListItem("--- Chọn ---", "  ")
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request("Certifiedid") Is Nothing AndAlso Request("Certifiedid") <> 0 Then
                hidID.Value = Request("Certifiedid")
                Load2Grid()
                BindToGrid()
            End If
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1)
        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            'lấy Mã GCN từ Id hồ sơ

            Dim _ParentId As Integer = 0
            Dim temp = (From q In data.CertifiedHouseholds
                           Where q.CertifiedID = hidID.Value Select q.ParentId).FirstOrDefault
            If Not temp Is Nothing Then
                _ParentId = temp
            End If

            Dim p As List(Of CertifiedHousehold)
            If _ParentId <> 0 Then
                p = (From q In data.CertifiedHouseholds
                     Where (q.ParentId = _ParentId Or q.CertifiedID = _ParentId) Order By q.CertifiedID Select q).ToList
            Else
                p = (From q In data.CertifiedHouseholds
                     Where q.CertifiedID = hidID.Value Or q.ParentId = hidID.Value Order By q.CertifiedID Select q).ToList
            End If

            Dim strKey_Name() As String = {"CertifiedID", "CertifiedIdOld", "Biz_VietName", "ParentId", "Ow_CardID", "CertifiedUp_Time", "CertifiedDate"}
            'Tong so ban ghi
            hidCount.Value = p.Count
            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities


            Dim _curHuyenId As Integer = Session("HuyenId")
            'load List PrositionDict
            Dim _j = (From q In _data.PositionDicts Order By q.Sort Select q).ToList
            With ddlCertifiedSignerPosition
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            With ddlCertifiedSignFor
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            'load list StaffDict
            Dim _SN = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedSignerName
                .DataSource = _SN
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            Dim _BH = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedBeHaft
                .DataSource = _BH
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With


            'load giấy đề nghị nếu có rồi
            'Dim intUserId As Integer = IIf(IsNothing(Session("UserID")), 0, Session("UserID"))
            'Dim use = (From q In _data.Users Where q.UserId = intUserId Select q.UserName).FirstOrDefault

            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

            CapNhatMCC.Visible = False
            If Not p Is Nothing Then
                'show link Update MCC
                If Not p.SoBienNhan Is Nothing Then
                    Using abc As New AutoDevModel.AutoDevEntities
                        Dim kkkk = (From q In abc.HoSoes Where q.SoBienNhan = p.SoBienNhan And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not kkkk Is Nothing Then
                            CapNhatMCC.Visible = True
                            hplLinkMcc.NavigateUrl = "../../Page/TiepNhan/UpdateMcc.aspx?s=" & kkkk.SoBienNhan.ToString
                            hplLinkMcc.Text = "đây"
                        End If
                    End Using
                End If


                'hidID.Value = p.CertifiedID
                'p.CertifiedStatus = 0 '0, chua duoc duyet
                If Not p.CertifiedCode Is Nothing AndAlso p.CertifiedCode <> "" Then
                    txtCertifiedCode.Text = p.CertifiedCode
                    If Not p.CertifiedDate Is Nothing Then
                        txtCertifiedDate.Text = CType(p.CertifiedDate, Date).ToString("dd/MM/yyyy")
                    Else

                        txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
                    End If

                    'txtCertifiedCode.Enabled = False
                Else
                    txtCertifiedCode.Text = btnGenGCN()
                End If
                'thong tin ca nhan


                'load CertifiedProvinderOrg by DeptCertifieds
                Dim _l = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList

                With ddlCertifiedProviderOrg
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                'load CertifiedDeptName by DeptCertifieds
                With ddlCertifiedDeptName
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                Dim _DoViCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "001" Order By q.Sort Select q.Name).FirstOrDefault
                Dim _PhongBanCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "002" Order By q.Sort Select q.Name).FirstOrDefault
                'Đơn vị cấp
                If Not p.CertifiedProviderOrg Is Nothing Then
                    ddlCertifiedProviderOrg.SelectedValue = p.CertifiedProviderOrg
                Else
                    ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                End If
                'Phòng ban cấp
                If Not p.CertifiedDeptName Is Nothing Then
                    ddlCertifiedDeptName.SelectedValue = p.CertifiedDeptName
                Else
                    ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                End If

                'chức vụ người được ký thay
                If Not p.CertifiedSignFor Is Nothing Then
                    ddlCertifiedSignFor.SelectedValue = p.CertifiedSignFor
                Else
                    ddlCertifiedSignFor.SelectedValue = ""
                End If
                'Tên Người được ký thay
                If Not p.CertifiedBeHaft Is Nothing Then
                    ddlCertifiedBeHaft.SelectedValue = p.CertifiedBeHaft
                Else
                    ddlCertifiedBeHaft.SelectedValue = ""
                End If
                'Người ký
                If Not p.CertifiedSignerName Is Nothing Then
                    ddlCertifiedSignerName.SelectedValue = p.CertifiedSignerName
                Else
                    ddlCertifiedSignerName.SelectedValue = ""
                End If
                'Chức vụ người ký
                If Not p.CertifiedSignerPosition Is Nothing Then
                    ddlCertifiedSignerPosition.SelectedValue = p.CertifiedSignerPosition
                Else
                    ddlCertifiedSignerPosition.SelectedValue = ""
                End If

                'lấy ngày cấp giấy lần đầu
                Dim _cerDateList = (From q In _data.CertifiedHouseholds Where q.ParentId = p.ParentId Select q).ToList()
                If _cerDateList.Count > 1 And p.CertifiedID <> p.ParentId Then
                    cerDateBegin.Visible = True
                    Dim _cerDateBegin = (From q In _data.CertifiedHouseholds Where q.CertifiedID = p.ParentId Select q).FirstOrDefault
                    If Not _cerDateBegin Is Nothing Then
                        txtCertifiedDateBegin.Text = IIf(IsNothing(_cerDateBegin.CertifiedDate) = True, "", CType(_cerDateBegin.CertifiedDate, Date).ToString("dd/MM/yyyy"))
                        hidCertifiedDateBegin.Value = IIf(IsNothing(_cerDateBegin.CertifiedID) = True, "", _cerDateBegin.CertifiedID)
                    End If
                Else
                    cerDateBegin.Visible = False
                End If
            End If

            'nút check ghi chú
            If _curHuyenId = 165 Then
                fromGhiChu.Visible = True
            Else
                fromGhiChu.Visible = False
            End If

        End Using
    End Sub
    Protected Function btnGenGCN() As String
        Dim strCode As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Using _data As New VSEntities
            Dim curCode As String = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            curCode = curCode & "800"
            Dim max As String = (From q In _data.CertifiedHouseholds Where q.ProvinceId = _curHuyenId And q.CertifiedCode.Contains(curCode) And q.CertifiedDate > "2014/01/01" Order By q.CertifiedCode Descending Select q.CertifiedCode).FirstOrDefault
            '52I80002416
            Dim HuyenCode = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            Try
                Dim _new As Integer = CType(max.Replace(HuyenCode, ""), Integer) + 1
                If _new > 0 Then
                    strCode = HuyenCode & _new.ToString.PadLeft(5)
                Else
                    strCode = HuyenCode & "800" & _new.ToString.PadLeft(5)
                End If
            Catch ex As Exception
                strCode = HuyenCode & "800" & "00001"
            End Try
            hidCertifiedCode.Value = strCode ' lưu vao hidden field để lưu
            txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
            Return strCode

        End Using
    End Function
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub

    Protected Sub btnExportWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportWord.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        Dim strFileName As String = strDocFile.Split("\")(strDocFile.Split("\").Length - 1)
        Excute_Javascript("SetDownFile('" & MainDomain & "GCNKD/" & strFileName & "');", Me.Page)
    End Sub
    Protected Sub btnExportPdf_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportPdf.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            Dim strFileName As String = strPdfFile.Split("\")(strPdfFile.Split("\").Length - 1)

            Response.Redirect(MainDomain & "GCNKD/" & strFileName)
        End If



    End Sub

    Function getDocFile() As String
        Dim strResult As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\HouseholdCertificate.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim cls As New clsDAPrint
                Dim dt As DataTable = cls.CertifiedHouseholdSelectById(hidID.Value, _curHuyenId)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    doc.MailMerge.Execute(dt)
                    'insert nganh nghe
                    Dim builder As DocumentBuilder = New DocumentBuilder(doc)

                    Dim strNganhNghe As String = ""
                    Dim strNganhNgheChiTiet As String = ""

                    Using _data As New VSEntities
                        Dim p = (From q In _data.CertifiedHouseholdNganhNghes Where q.CertifiedID = hidID.Value Select q).ToList
                        For Each a In p
                            Dim nganhnghe = (From k In _data.DanhMucNganhNghes Where k.Id = a.DanhMucNganhNgheID Select k).FirstOrDefault
                            strNganhNghe = strNganhNghe & nganhnghe.Name & " (" & nganhnghe.Code & ")" & ". "
                            strNganhNgheChiTiet = strNganhNgheChiTiet & a.Description & ". "
                            'If Not a.Description Is Nothing AndAlso a.Description <> "" Then
                            '    strNganhNghe = strNganhNghe & a.Description & " (" & nganhnghe.Code & ")" & ", "
                            'Else
                            '    strNganhNghe = strNganhNghe & nganhnghe.Name & " (" & nganhnghe.Code & ")" & ", "
                            'End If
                        Next


                        'cap lan dau CertifiedDateFirst

                        Dim lstOfCertified As List(Of CertifiedHousehold)
                        Dim curCertified = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

                        If Not curCertified Is Nothing AndAlso curCertified.ParentId <> 0 Then
                            lstOfCertified = (From q In _data.CertifiedHouseholds
                                 Where (q.ParentId = curCertified.ParentId Or q.CertifiedID = curCertified.ParentId) Order By q.CertifiedDate Select q).ToList
                        Else
                            lstOfCertified = (From q In _data.CertifiedHouseholds
                                 Where q.CertifiedID = hidID.Value Or q.ParentId = hidID.Value Order By q.CertifiedDate Select q).ToList
                        End If

                        ' Dim lstOfCertified = (From q In _data.CertifiedHouseholds Where q.CertifiedCode = txtCertifiedCode.Text And (q.ParentId = hidID.Value Or q.CertifiedID = hidID.Value) Order By q.CertifiedUp_Time Ascending Select q).ToList

                        Dim i = 0
                        For Each a In lstOfCertified
                            Dim _date As Date = CType(a.CertifiedDate, Date)
                            If i = 0 Then
                                builder.MoveToMergeField("CertifiedDateFirst")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim lblDate As String = ""
                                    builder.Write(_date.Day & " tháng " & _date.Month & " năm " & _date.Year)
                                    'không có cấp đổi or cấp lại
                                Else
                                    builder.Write("")
                                End If

                            End If
                            'xem có phải là giấy cấp lại
                            If i = 1 And (i = lstOfCertified.Count - 1) And curCertified.CertifiedStatus = "L" Then
                                builder.MoveToMergeField("CertifiedSecond")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký cấp lại lần thứ: 1 ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            Else
                                builder.MoveToMergeField("CertifiedSecond")
                                builder.Write("")
                            End If
                            'ko phai lan dau va cap hon 2 lan
                            If (i = lstOfCertified.Count - 1) And (lstOfCertified.Count > 2) And curCertified.CertifiedStatus = "L" Then
                                builder.MoveToMergeField("CertifiedSecond")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký thay đổi lần thứ: " & i.ToString & " ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            Else
                                builder.MoveToMergeField("CertifiedSecond")
                                builder.Write("")
                            End If

                            'còn lại là giấy cấp đổi
                            If i = 1 And (i = lstOfCertified.Count - 1) And curCertified.CertifiedStatus = "D" Then
                                builder.MoveToMergeField("CertifiedSecond")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký thay đổi lần thứ: 1 ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            Else
                                builder.MoveToMergeField("CertifiedSecond")
                                builder.Write("")
                            End If
                            'ko phai lan dau va cap hon 2 lan
                            If (i = lstOfCertified.Count - 1) And (lstOfCertified.Count > 2) And curCertified.CertifiedStatus = "D" Then
                                builder.MoveToMergeField("CertifiedSecond")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký thay đổi lần thứ: " & i.ToString & " ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            Else
                                builder.MoveToMergeField("CertifiedSecond")
                                builder.Write("")
                            End If
                            i = i + 1
                        Next

                        ' ky thay
                        Dim kt = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault
                        If Not kt Is Nothing Then
                            ' vốn kinh doanh
                            If Not kt.Biz_InvestCapital Is Nothing Then
                                builder.MoveToMergeField("Biz_InvestCapital_Name")
                                builder.Write(FormatCurrency(kt.Biz_InvestCapital).Replace(",", ".")) 'vốn kinh doanh

                            End If

                            If Not kt.CertifiedSignFor Is Nothing AndAlso kt.CertifiedSignFor.Trim <> "" Then
                                builder.MoveToMergeField("CertifiedSignerFor")
                                builder.Write("KT. " & kt.CertifiedSignFor.ToUpper)
                            Else
                                builder.MoveToMergeField("CertifiedSignerFor")
                                builder.Write("")
                            End If
                            'ngay sinh
                            If kt.Ow_BirthDate.Length >= 8 And kt.Ow_BirthDate.IndexOf("/") < 0 Then
                                builder.MoveToMergeField("Ow_BirthDate_Name")
                                Dim strDate As String = kt.Ow_BirthDate.Substring(0, 2) & "/" & kt.Ow_BirthDate.Substring(2, 2) & "/" & kt.Ow_BirthDate.Substring(4, 4)
                                builder.Write(strDate)
                            Else
                                builder.MoveToMergeField("Ow_BirthDate_Name")
                                builder.Write(kt.Ow_BirthDate)
                            End If

                            'ngay cap cmnd
                            If Not kt.Ow_CardDate Is Nothing Then
                                builder.MoveToMergeField("Ow_CardDate_Name")
                                builder.Write(CType(kt.Ow_CardDate, Date).ToString("dd/MM/yyyy"))
                            Else
                                builder.MoveToMergeField("Ow_CardDate_Name")
                                Write("")
                            End If

                            ' gioi tinh
                            If kt.Ow_Sex = 1 Then
                                builder.MoveToMergeField("Ow_Sex_Name")
                                builder.Write("Nam")
                            Else
                                builder.MoveToMergeField("Ow_Sex_Name")
                                builder.Write("Nữ")
                            End If
                            ' loại giấy tờ
                            If kt.Ow_Doc_ID = "" Or kt.Ow_Doc_ID = "0" Then
                                builder.MoveToMergeField("Ow_Doc_ID_Name")
                                builder.Write("Giấy chứng minh nhân dân")
                            Else
                                Dim strLoaiGiay = (From q In _data.CertifiedPaperDicts Where q.Id = kt.Ow_Doc_ID Select q).FirstOrDefault
                                If Not strLoaiGiay Is Nothing Then
                                    builder.MoveToMergeField("Ow_Doc_ID_Name")
                                    builder.Write(strLoaiGiay.Name)
                                End If
                            End If


                        End If

                        'noted
                        Dim _huyen = (From q In _data.Configs Where q.ProvinceId = _curHuyenId Select q).FirstOrDefault

                        If Not _huyen Is Nothing AndAlso Not _huyen.Ref2 Is Nothing Then
                            'check trường hợp GCN lúc có ghi chú lúc không
                            If Not _huyen.Ref3 Is Nothing Then
                                If chkCheckGhiChu.Checked Then
                                    builder.MoveToMergeField("Noted")
                                    builder.Write(_huyen.Ref2)
                                Else
                                    builder.MoveToMergeField("Noted")
                                    builder.Write("")
                                End If
                            Else
                                builder.MoveToMergeField("Noted")
                                builder.Write(_huyen.Ref2)
                            End If
                        Else
                            builder.MoveToMergeField("Noted")
                            builder.Write("")
                        End If
                        'gop von kinh doanh
                        Dim lstGopVon = (From q In _data.CertifiedHouseholdMembers Where q.CertifiedID = hidID.Value Select q).ToList
                        If Not lstGopVon Is Nothing AndAlso lstGopVon.Count > 0 Then

                            'header gop von
                            builder.MoveToMergeField("TitleSection6")
                            builder.InsertHtml("<b style='font-size:19px' ><font face='Times New Roman'> 6. Danh sách cá nhân góp vốn thành lập hộ kinh doanh</font></b>")

                            Dim strHMLBeginTable As String = "<table border='1' cellspacing='0' cellpadding='0' style='width:100%;border-collapse:collapse;'>"
                            strHMLBeginTable = strHMLBeginTable & "<tr><td style='valign=top' align ='center'>STT</td><td width='110'  style='valign=top' align ='center'>Tên thành viên</td><td  style='valign=top' align ='center'>Nơi đăng ký hộ khẩu thường trú</td><td align ='center'>Giá trị phần vốn góp (VNĐ)" & _
                                "</td><td align ='center'>Tỷ lệ (%)</td><td width='120'  style='valign=top' align ='center'>Số giấy chứng minh nhân dân (hoặc chứng thực cá nhân hợp pháp khác)</td><td  style='valign=top' align ='center'>Ghi chú</td></tr>"

                            Dim strHTMLEndTable As String = "</table>"
                            Dim strHTML As String = ""
                            'danh sach gop von
                            Dim _Stt As Integer = 1
                            For Each a In lstGopVon
                                strHTML = strHTML & "<tr>"
                                strHTML = strHTML & "<td align ='center'>" & _Stt.ToString & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberName & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberAddress & "</td>"
                                Dim _Money As String = ""
                                Try
                                    _Money = FormatCurrency(a.MemberValues).Replace(",", ".") & " đ"
                                Catch ex As Exception
                                    _Money = a.MemberValues
                                End Try

                                strHTML = strHTML & "<td align ='center'>" & _Money & "</td>"
                                strHTML = strHTML & "<td align ='center'>" & a.MemberRate & "</td>"
                                strHTML = strHTML & "<td align ='center'>" & a.MemberCard & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberDes & "</td>"
                                strHTML = strHTML & "</tr>"
                                _Stt = _Stt + 1
                            Next
                            builder.MoveToMergeField("Section6")
                            builder.InsertHtml(strHMLBeginTable & strHTML & strHTMLEndTable)
                        Else
                            builder.MoveToMergeField("TitleSection6")
                            builder.InsertHtml("")
                            builder.MoveToMergeField("Section6")
                            builder.Write("")
                        End If

                    End Using
                    builder.MoveToMergeField("Biz_Career")
                    builder.Write(strNganhNghe.Trim.TrimEnd(","))

                    builder.MoveToMergeField("Biz_Career_Chitiet")
                    builder.Write(strNganhNgheChiTiet.Trim.TrimEnd(","))

                    strResult = applicationPath & "GCNKD"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    'set filename = soCN

                    strResult &= txtCertifiedCode.Text & "-" & Format(Now, "yyyyMMddfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        doc = Nothing
                    End If


                End If

            End If

        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/QuanLyHoSo/List.aspx';", Me.Page, True)
        End Try

        Return strResult
    End Function

    Protected Sub UpdateThongtin()
        ' If hidCertifiedCode.Value <> "" Then
        Using _data As New VSEntities
            Dim p = (From k In _data.CertifiedHouseholds Where k.CertifiedID = hidID.Value Select k).FirstOrDefault
            If Not p Is Nothing Then
                p.CertifiedDate = StringToDate(txtCertifiedDate.Text)

                If p.ParentId = 0 Then
                    p.CertifiedUp_Time = 1
                Else 'cung parent id
                    If Not p.CertifiedUp_Time Is Nothing Then
                        p.CertifiedUp_Time = p.CertifiedUp_Time
                    Else
                        p.CertifiedUp_Time = (From q In _data.CertifiedHouseholds Where q.ParentId = p.ParentId Select q).Count + 1
                    End If
                End If


                p.CertifiedCode = txtCertifiedCode.Text
                'Đơn vị cấp
                p.CertifiedProviderOrg = ddlCertifiedProviderOrg.SelectedValue
                'Phòng ban cấp
                p.CertifiedDeptName = ddlCertifiedDeptName.SelectedValue
                'Thay mặt Người ký
                p.CertifiedSignFor = ddlCertifiedSignFor.SelectedValue
                'Tên Người ký thay
                p.CertifiedBeHaft = ddlCertifiedBeHaft.SelectedValue
                'Người ký
                p.CertifiedSignerName = ddlCertifiedSignerName.SelectedValue
                'Chức vụ người ký
                p.CertifiedSignerPosition = ddlCertifiedSignerPosition.SelectedValue
                _data.SaveChanges()
            End If
        End Using
        'End If
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        Using _data As New VSEntities
            If e.Row.RowIndex >= 0 Then
                Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
                lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1



                Dim lnkCapNhat As LinkButton = CType(e.Row.FindControl("lnkCapNhat"), LinkButton)

                Dim hplBiz_VietName As HyperLink = CType(e.Row.FindControl("hplBiz_VietName"), HyperLink)
                hplBiz_VietName.NavigateUrl = "../../Page/CertifiedHousehold/Detail.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
                hplBiz_VietName.Text = grdShow.DataKeys(e.Row.RowIndex)("Biz_VietName").ToString

                Dim hplParentId As HyperLink = CType(e.Row.FindControl("hplParentId"), HyperLink)
                'lấy danh sách cấp đổi lần thứ mấy show ra list xem thành phần hồ sơ trong detail
                Dim _parId As Integer = grdShow.DataKeys(e.Row.RowIndex)("ParentId")
                Dim _cerID As Integer = grdShow.DataKeys(e.Row.RowIndex)("CertifiedID")
                If grdShow.DataKeys(e.Row.RowIndex)("ParentId") <> grdShow.DataKeys(e.Row.RowIndex)("CertifiedID") Then
                    Dim _CerList = (From q In _data.CertifiedHouseholds Where q.CertifiedID = _cerID Select q.CertifiedUp_Time).FirstOrDefault

                    hplParentId.Text = "Cấp đổi lần "
                Else
                    hplParentId.Text = "Đăng ký lần đầu"
                End If
                Dim rCer = (From q In _data.CertifiedHouseholds Where q.CertifiedID = _cerID Select q).FirstOrDefault
                Dim txtOw_CardIDgrd As TextBox = CType(e.Row.FindControl("txtOw_CardIDgrd"), TextBox)
                Dim Ow_CardIDgrd = grdShow.DataKeys(e.Row.RowIndex)("Ow_CardID")
                If Not Ow_CardIDgrd Is Nothing Then
                    txtOw_CardIDgrd.Text = grdShow.DataKeys(e.Row.RowIndex)("Ow_CardID").ToString
                Else
                    txtOw_CardIDgrd.Text = ""
                End If

                Dim txtCertifiedDategrd As TextBox = CType(e.Row.FindControl("txtCertifiedDategrd"), TextBox)
                Dim CertifiedDate = grdShow.DataKeys(e.Row.RowIndex)("CertifiedDate")
                If Not CertifiedDate Is Nothing Then
                    txtCertifiedDategrd.Text = CType((grdShow.DataKeys(e.Row.RowIndex)("CertifiedDate")), Date).ToString("dd/MM/yyyy")
                Else

                    txtCertifiedDategrd.Text = Now.Date.ToString("dd/MM/yyyy")
                End If

                Dim txtCertifiedUp_Timegrd As TextBox = CType(e.Row.FindControl("txtCertifiedUp_Timegrd"), TextBox)
                Dim CertifiedUp_Timegrd = grdShow.DataKeys(e.Row.RowIndex)("CertifiedUp_Time")
                If Not CertifiedUp_Timegrd Is Nothing Then
                    txtCertifiedUp_Timegrd.Text = grdShow.DataKeys(e.Row.RowIndex)("CertifiedUp_Time").ToString
                Else

                    txtCertifiedUp_Timegrd.Text = ""
                End If


                hplParentId.NavigateUrl = "../../Page/QuanlyHoSo/CapGCN.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString

            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub

    Protected Sub btnUpdateCertifiedDate_Click(sender As Object, e As EventArgs) Handles btnUpdateCertifiedDate.Click
        Using _data As New VSEntities
            Dim _cerId As Integer = hidCertifiedDateBegin.Value
            Dim _curHuyenId As Integer = Session("HuyenId")
            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = _cerId And q.ProvinceId = _curHuyenId Select q).FirstOrDefault
            If Not p Is Nothing Then
                p.CertifiedDate = DateToString(txtCertifiedDateBegin.Text.Trim()) ' ngày cấp lần đầu
                _data.SaveChanges()
                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/QuanlyHoSo/CapGCN.aspx?Certifiedid=" & Request("Certifiedid") & "';", Me.Page, True)
            End If
        End Using

    End Sub

    Protected Sub btnSaveThongTin_Click(sender As Object, e As EventArgs) Handles btnSaveThongTin.Click
        UpdateThongtin()
        Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/QuanlyHoSo/CapGCN.aspx?Certifiedid=" & Request("Certifiedid") & "';", Me.Page, True)
    End Sub
    Protected Sub btnUpdate_Click(sender As Object, e As System.EventArgs) Handles btnUpdate.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim txtCertifiedUp_Timegrd As New TextBox
                    txtCertifiedUp_Timegrd = CType(item.FindControl("txtCertifiedUp_Timegrd"), TextBox)
                    Dim txtOw_CardIDgrd As New TextBox
                    txtOw_CardIDgrd = CType(item.FindControl("txtOw_CardIDgrd"), TextBox)
                    Dim txtCertifiedDategrd As New TextBox
                    txtCertifiedDategrd = CType(item.FindControl("txtCertifiedDategrd"), TextBox)
                    intTotal += 1
                    intId = grdShow.DataKeys(item.RowIndex)("CertifiedID").ToString
                    Dim q = (From p In data.CertifiedHouseholds Where p.CertifiedID = intId Select p).FirstOrDefault
                    Try

                        q.CertifiedUp_Time = txtCertifiedUp_Timegrd.Text.Trim()
                        q.Ow_CardID = txtOw_CardIDgrd.Text
                        q.CertifiedDate = StringToDate(txtCertifiedDategrd.Text)
                        data.SaveChanges()
                        intCount += 1
                    Catch ex As Exception
                    End Try

                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Update dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Update dữ liệu thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using

    End Sub

End Class

